import logging
from logging.handlers import RotatingFileHandler
from flask import Flask,render_template
from flask import g
from flask_sqlalchemy import SQLAlchemy
from flask_session import Session
import redis

from iHome.utils.common import ReagxConvertr

redis_store=None
from config import config_dict
db=SQLAlchemy()

def log_file(LV):
    logging.basicConfig(level=LV)
    file_log_handler=RotatingFileHandler("logs/log",maxBytes=1024*1024*100,backupCount=10)
    formatter=logging.Formatter("%(levelname)s %(filename)s :%(lineno)d%(message)s")
    file_log_handler.setFormatter(formatter)
    logging.getLogger().addHandler(file_log_handler)
def create_app(env):
    app=Flask(__name__)
    config_classname = config_dict[env]
    log_file(config_classname.LOG_LV)

    app.config.from_object(config_classname)
    db.init_app(app)
    Session(app)
    app.url_map.converters['re'] = ReagxConvertr
    global redis_store
    redis_store=redis.StrictRedis(host=config_classname.REDIS_HOST,port=config_classname.REDIS_PORT)
    # 注册蓝图
    from iHome.api_1_0 import api


    app.register_blueprint(api)


    # 注册静态html访问的蓝图
    from .web_html import html
    app.register_blueprint(html)



    from flask_wtf import CSRFProtect
    CSRFProtect(app)
    from flask_wtf.csrf import generate_csrf
    @app.after_request
    def after_request(response):
        csrf_token=generate_csrf()
        response.set_cookie("csrf_token",csrf_token)
        return response

    return app